/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.pb.diplom.first.business;

import com.pb.diplom.first.dao.ProducerDao;
import com.pb.diplom.first.dbProp.DbProperties;
import com.pb.diplom.first.tables.Producer;
import static java.lang.Thread.sleep;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Slava
 */
public class DbStorageProducer {

    private final static DbStorageProducer instance = new DbStorageProducer();
    private final Map<Long, Producer> producers = new HashMap<>();
    Producer producerss = new Producer();
    private Long uniqueIndex = 0L;
    ProducerDao dao = new ProducerDao(DbProperties.LOGIN, DbProperties.PASSWORD, DbProperties.URL);

    private DbStorageProducer() {
        init();
    }

    public static DbStorageProducer getInstance() {
        return instance;
    }

    private void init() {
        try {
            List<Producer> pr = dao.getAll();
            for (Producer prod : pr) {
                producers.put(prod.getId(), new Producer(prod.getId(), prod.getName()));
            }

        } catch (SQLException ex) {
            throw new RuntimeException("Error on reading data from db", ex);
        }
    }

    public Producer saveOrUpdate(Producer producer) throws SQLException {
        dao.save1(producer);
        //sleep(1000);
        Producer item = producer.getId() != null
                ? producer : new Producer(dao.getId(producer), producer.getName());
        producers.put(dao.getId(item), item);
        return item;
    }

    public Collection<Producer> getProducers() {
        return producers.values();
    }

    public Object[][] getProducersAsTable() throws SQLException {
        Object[][] result = new Object[producers.size()][2];
        int index = 0;
        for (Producer producer : dao.getAll()) {
            result[index][0] = producer.getId();
            result[index][1] = producer.getName();
            index++;
        }
        return result;
    }

}
